package com.lxk.controller.admin;

import com.lxk.common.GsonUtils;
import com.lxk.domain.UserDbEntity;
import com.lxk.service.UserService;
import com.lxk.service.component.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by Lxk on 2020/6/13.
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class BIndexController {

    @Resource
    private UserService userService;

    @Resource
    private RedisClient redisClient;

    @GetMapping
    public String admin(){
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password
            , HttpServletRequest request, HttpServletResponse response, RedirectAttributes attributes){
        UserDbEntity user = userService.checkUser(username,password);
        if(user != null){
            String redisKey = UUID.randomUUID().toString().replace("-","");
            response.addCookie(new Cookie("ticket", redisKey));
            String redisValue = GsonUtils.getGson().toJson(user);
            boolean res = redisClient.setex(redisKey, redisValue,60*60*5);
            log.info("setex redisKey:{} ,value:{}, res:{}",redisKey,redisValue,res);
            return "admin/index";
        }else{
            attributes.addFlashAttribute("message","用户名或密码错误！！");
            return "redirect:/admin";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }


}
